package com.lagou.zuoye.dao;


import com.lagou.zuoye.util.DbUtil;
import com.lagou.zuoye.bean.User;
import com.lagou.zuoye.util.DruidUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDaoImp implements UserDao {
    @Override
    public User userLogin(User user) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet =null;
        try {
            //1.获取数据库连接
            connection = DbUtil.getConnection();
            //2.编写SQL语句
            String sql = "select * from t_user where userName = ? and password = ?";
            //3.制行sql语句获取结果集并返回
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,user.getUserName());
            preparedStatement.setString(2,user.getPassword());

            //获取结果集
            resultSet = preparedStatement.executeQuery();
            if(resultSet.next()){
                User user1 = new User(resultSet.getString("userName"),resultSet.getString("password"));
                return user1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //4.释放资源
            try {
                DbUtil.closeResource(connection,preparedStatement);
                if(null!=resultSet) {
                    resultSet.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return null;

//        Connection connection = null;
//        PreparedStatement preparedStatement = null;
//        ResultSet resultSet =null;
//
//        try {
//            connection = DruidUtil.getConnection();
//            String sql = "select * from t_user where userName = ? and password = ?";
//            preparedStatement = connection.prepareStatement(sql);
//            preparedStatement.setString(1,user.getUserName());
//            preparedStatement.setString(2,user.getPassword());
//            ResultSet res = preparedStatement.executeQuery();
//            if(res.next()){
//                User user1 = new User(resultSet.getString("userName"),resultSet.getString("password"));
//                return user1;
//            }
//        } catch (SQLException e) {
//            e.printStackTrace();
//        } finally {
//            DruidUtil.close(connection,preparedStatement,resultSet);
//        }
//        return null;
    }
}
